package com.broada.apm.logic;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;

import com.broada.apm.es.indices.service.IndexService;
import com.broada.apm.es.indices.service.impl.IndexServiceImpl;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

public class IndexDelayDeleteManager {
	private static IndexDelayDeleteManager manager = new IndexDelayDeleteManager();
	private IndexService indexService = new IndexServiceImpl();
	private Cache<String, String> cache;

	public IndexDelayDeleteManager() {
		cache = CacheBuilder.newBuilder().removalListener(new RemovalListener<String, String>() {
			@Override
			public void onRemoval(RemovalNotification<String, String> notification) {
				indexService.deleteIndex("apm_perf_y" + notification.getKey() + "*", "apm_perf_a" + notification
						.getKey() + "*");
			}
		}).expireAfterWrite(5, TimeUnit.MINUTES).build();
	}

	public static IndexDelayDeleteManager getInstance() {
		return manager;
	}

	public void pushToDelayRemoveCache(String appId) {
		if (!StringUtils.isBlank(appId))
			cache.put(appId, appId);
	}
}
